<template>
    <div class="countDownBox" v-if="s>=0">
        <template v-if="type==1">
            <template v-if="parseInt(d)>0">
                <em>{{d}} </em> day &nbsp;
            </template>
            <em>{{h}}</em> : 
            <em>{{m}}</em> : 
            <em>{{s}}</em>  
        </template>
        <template v-else-if="type==2">
            <em>{{d>0?(d*24+h):h}}</em> :  
            <em>{{m}}</em> :  
            <em>{{s}}</em>  
        </template>
    </div>
</template>

<script>
import { reactive,toRefs,onMounted,onBeforeUnmount} from 'vue'
export default {
    props:{
        dataTime:String,
        type:{
            type:Number,  // 1显示天时分秒，2显示时分秒，3显示分秒
            default:1
        }
    },
    setup(props,context){
        const state = reactive({
            d:'', // 天
            h:'', //  时
            m:'', // 分
            s:'',  // 秒
            st:''
        })

        onMounted(()=>{
            showtime()
        })

        onBeforeUnmount(()=>{  // 销毁组件
            clearTimeout(state.st)
        })

        const showtime = ()=>{
            let nowtime = new Date()  //获取当前时间 
            let endtime = new Date(props.dataTime.replace(/-/g,"/"))  //定义结束时间
            let lefttime = endtime.getTime() - nowtime.getTime()  //距离结束时间的毫秒数
            state.d = Math.floor(lefttime/(1000*60*60*24))  //计算天数
            state.h = Math.floor(lefttime/(1000*60*60)%24)  //计算小时数
            state.m = Math.floor(lefttime/(1000*60)%60)  //计算分钟数
            state.s = Math.floor(lefttime/1000%60) //计算秒数
           // return leftd + "天" + lefth + ":" + leftm + ":" + lefts;  //返回倒计时的字符串
            //state.d<10 && (state.d = '0'+state.d)
            state.h<10 && (state.h = '0'+state.h)
            state.m<10 && (state.m = '0'+state.m)
            state.s<10 && (state.s = '0'+state.s)
            state.st = setTimeout(()=>{
                showtime()
            },1000)
        }

        return{
            ...toRefs(state),
            showtime
        }
    }
}
</script>

<style lang="scss" scoped>
    .countDownBox{
        display: flex;
        line-height: normal;
        align-items: center;
        font-family: Poppins-Medium, Poppins;
        font-weight: 500;
        line-height: normal;
        color: #fff;
        font-size: 38px;  
        em{
            font-style: normal;  
        }  
    }
</style>